package com.example.h1nson.realphotography.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.example.h1nson.realphotography.R;
import com.example.h1nson.realphotography.activity.imageloader.ImageGridActivity;
import com.example.h1nson.realphotography.activity.updateHead.ImagesGridActivity;
import com.example.h1nson.realphotography.asyncTask.UploadPhotoAsynTask;
import com.example.h1nson.realphotography.config.ConfigURL;
import com.example.h1nson.realphotography.config.GetCurrentUser;
import com.example.h1nson.realphotography.entity.Photo;
import com.example.h1nson.realphotography.interface_photo.OnDataFinishedListener;
import com.pizidea.imagepicker.AndroidImagePicker;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.List;

public class CameraActivity extends AppCompatActivity implements AndroidImagePicker.OnImageCropCompleteListener,BDLocationListener{
    private ImageView imageView;
    private TextView textViewName;
    private TextView textViewAddress;
    private TextView textViewDate;
    private Button btnUpload;
    private ImageButton back;
    private Bitmap bitmap;
    private boolean hasBitmap;
    public LocationClient mLocationClient = null;
    private LocationClientOption mOption;
    private String address;
    private double longitude,latitude;
    //public BDLocationListener myListener = new MyLocationListener();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        imageView = (ImageView)findViewById(R.id.imageUplod);
        textViewName = (TextView)findViewById(R.id.textName);
        textViewAddress = (TextView)findViewById(R.id.textAddress);
        textViewDate = (TextView)findViewById(R.id.textDate);
        btnUpload = (Button)findViewById(R.id.btn_upload_photo) ;
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.setLocOption(getDefaultLocationClientOption());
        mLocationClient.registerLocationListener(this);
        mLocationClient.start();
        setUI();
    }

    public LocationClientOption getDefaultLocationClientOption(){
        if(mOption == null){
            mOption = new LocationClientOption();
            mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
            mOption.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系，如果配合百度地图使用，建议设置为bd09ll;
            mOption.setScanSpan(3000);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
            mOption.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
            mOption.setIsNeedLocationDescribe(true);//可选，设置是否需要地址描述
            mOption.setNeedDeviceDirect(false);//可选，设置是否需要设备方向结果
            mOption.setLocationNotify(false);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
            mOption.setIgnoreKillProcess(true);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
            mOption.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
            mOption.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
            mOption.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        }
        return mOption;
    }
    //设置界面
    private void setUI(){
        hasBitmap=false;
        //设置选中图片
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        ViewGroup.LayoutParams ps = imageView.getLayoutParams();
        ps.height = width;
        ps.width =width;
        imageView.setLayoutParams(ps);
        imageView.setImageResource(R.drawable.camera);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AndroidImagePicker.getInstance().setSelectMode(AndroidImagePicker.Select_Mode.MODE_SINGLE);
                AndroidImagePicker.getInstance().setShouldShowCamera(true);
                Intent intent = new Intent();
                intent.putExtra("isCrop", true);
                int requestCode = 1435;
                intent.setClass(CameraActivity.this,ImagesGridActivity.class);
                startActivityForResult(intent, requestCode);
            }
        });
        //显示发布人昵称
        textViewName.setText(GetCurrentUser.currentUser.getUserName());
        //显示发布时间
        textViewDate.setText("2016-5-16");
        Date curDate = new Date(System.currentTimeMillis());
        textViewDate.setText(1900+curDate.getYear()+"-"+(1+curDate.getMonth())+"-"+curDate.getDate());
        //显示发布地点
        textViewAddress.setText("北京交通大学");
        //设置提交按钮
        btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (hasBitmap) {
                    btnUpload.setEnabled(false);
                    String address = textViewAddress.getText().toString();
                    Date curDate = new Date(System.currentTimeMillis());
                    String URL = GetCurrentUser.currentUser.getUserId()+"_"+System.currentTimeMillis() + ".bmp";
                    int owner = GetCurrentUser.currentUser.getUserId();
                    int nageNum = 0;
                    int actNum = 0;

                    Photo photo = new Photo(owner,URL,longitude,latitude,address, curDate, nageNum, actNum);
                    UploadPhotoAsynTask uploadPhotoAsynTask = new UploadPhotoAsynTask(photo, bitmap);
                    uploadPhotoAsynTask.setOnDataFinishedListener(new OnDataFinishedListener() {
                        @Override
                        public void onDataSuccessfully(Object data) {
                            JSONObject jsonObject;
                            ;
                            try {
                                jsonObject = new JSONObject(data.toString());
                                String result = jsonObject.getString("result");
                                if(result.equals("uploadPhotoSuccess")) {
                                    finish();
                                    Toast.makeText(CameraActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                                    Intent i = new Intent(CameraActivity.this,ImageGridActivity.class);
                                    i.putExtra("serverURL", ConfigURL.myPhotoURL);
                                    startActivity(i);
                                }
                                else {
                                    Toast.makeText(CameraActivity.this,"发布失败，请重试",Toast.LENGTH_SHORT).show();
                                    btnUpload.setEnabled(true);
                                }
                            }
                            catch (JSONException e){
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onDataFailed() {
                            btnUpload.setEnabled(true);
                        }
                    });
                    uploadPhotoAsynTask.execute();
                }else {
                    Toast.makeText(CameraActivity.this, "请选择图片资源", Toast.LENGTH_SHORT).show();
                    btnUpload.setEnabled(true);
                }
            }
        });

    }

    @Override
    public void onImageCropComplete(Bitmap bmp, float ratio) {
        hasBitmap = true;
        bitmap = bmp;
        System.out.println("上传图片");
        if(bitmap!=null) {
            imageView.setImageBitmap(bitmap);
        }
    }
    @Override
    protected void onResume() {
        AndroidImagePicker.getInstance().addOnImageCropCompleteListener(this);
        super.onResume();

    }

    @Override
    public void onReceiveLocation(BDLocation location) {
        //Receive Location
        StringBuffer sb = new StringBuffer(256);
        sb.append("time : ");
        sb.append(location.getTime());
        sb.append("\nerror code : ");
        sb.append(location.getLocType());
        sb.append("\nlatitude : ");
        sb.append(location.getLatitude());
        sb.append("\nlontitude : ");
        sb.append(location.getLongitude());
        sb.append("\nradius : ");
        sb.append(location.getRadius());
        if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位结果
            sb.append("\nspeed : ");
            sb.append(location.getSpeed());// 单位：公里每小时
            sb.append("\nsatellite : ");
            sb.append(location.getSatelliteNumber());
            sb.append("\nheight : ");
            sb.append(location.getAltitude());// 单位：米
            sb.append("\ndirection : ");
            sb.append(location.getDirection());// 单位度
            sb.append("\naddr : ");
            sb.append(location.getAddrStr());
            sb.append("\ndescribe : ");
            sb.append("gps定位成功");

        } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 网络定位结果
            sb.append("\naddr : ");
            sb.append(location.getAddrStr());
            //运营商信息
            sb.append("\noperationers : ");
            sb.append(location.getOperators());
            sb.append("\ndescribe : ");
            sb.append("网络定位成功");
        } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
            sb.append("\ndescribe : ");
            sb.append("离线定位成功，离线定位结果也是有效的");
        } else if (location.getLocType() == BDLocation.TypeServerError) {
            sb.append("\ndescribe : ");
            sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
        } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
            sb.append("\ndescribe : ");
            sb.append("网络不同导致定位失败，请检查网络是否通畅");
        } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
            sb.append("\ndescribe : ");
            sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
        }
        sb.append("\nlocationdescribe : ");
        sb.append(location.getLocationDescribe());// 位置语义化信息
        address = location.getLocationDescribe();
        List<Poi> list = location.getPoiList();// POI数据
        if (list != null) {
            sb.append("\npoilist size = : ");
            sb.append(list.size());
            for (Poi p : list) {
                sb.append("\npoi= : ");
                sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
            }
        }
        System.out.println("BaiduLocationApiDem"+sb.toString());
        textViewAddress.setText(address);
        longitude = location.getLongitude();
        latitude = location.getLatitude();
        mLocationClient.stop();
    }
}
